part of common_lib_plugin;

class ImageCompressUtil {
  static ImageCompressUtil? _instance;

  ImageCompressUtil._();

  static ImageCompressUtil instance() {
    return (_instance != null) ? _instance! : _init();
  }

  static ImageCompressUtil _init() {
    _instance = ImageCompressUtil._();
    return _instance!;
  }

  /// 图片压缩 File -> File, 只支持jpg和jpeg
  Future<File> imageCompressAndGetFile(File file) async {
    logWTF(file.lengthSync().toString());
    if (file.lengthSync() < 2 * 1024 * 1024) {
      return file;
    }
    var quality = 100;
    if (file.lengthSync() > 30 * 1024 * 1024) {
      quality = 20;
    } else if (file.lengthSync() > 15 * 1024 * 1024) {
      quality = 40;
    } else if (file.lengthSync() > 10 * 1024 * 1024) {
      quality = 60;
    } else if (file.lengthSync() > 6 * 1024 * 1024) {
      quality = 80;
    }
    var dir = await path_provider.getTemporaryDirectory();
    var targetPath = "${dir.absolute.path}/${DateTime.now().millisecondsSinceEpoch}.jpg";

    var result = await FlutterImageCompress.compressAndGetFile(
      file.absolute.path,
      targetPath,
      minWidth: 600,
      quality: quality,
      rotate: 0,
    );

    logD("压缩前：${file.lengthSync() / 1024}");

    logD("压缩后：${(await result?.length() ?? 0) / 1024}");

    return result != null ? File(result.path) : file;
  }

  /// 图片压缩 File -> Uint8List
  Future<Uint8List> imageCompressFile(File file) async {
    var result = await FlutterImageCompress.compressWithFile(
      file.absolute.path,
      minWidth: 2300,
      minHeight: 1500,
      quality: 94,
      rotate: 90,
    );
    return result!;
  }

  /// 图片压缩 Asset -> Uint8List
  Future<Uint8List> imageCompressAsset(String assetName) async {
    var list = await FlutterImageCompress.compressAssetImage(
      assetName,
      minHeight: 1920,
      minWidth: 1080,
      quality: 96,
      rotate: 180,
    );

    return list!;
  }

  /// 图片压缩 Uint8List -> Uint8List
  Future<Uint8List> testComporessList(Uint8List list) async {
    var result = await FlutterImageCompress.compressWithList(list, minHeight: 1920, minWidth: 1080, quality: 96, rotate: 135, format: CompressFormat.png);
    return result;
  }

  bool imageValidated(File file) {
    if (file.lengthSync() > 8 * 1024 * 1024) {
      return true;
    } else {
      return false;
    }
  }
}
